package com.eqdd.yiqidian.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.annotation.api.DealCodeInjector;
import com.eqdd.annotation.datasave.DealCodeClass;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.TongxunluFragmentCustom;
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.CodeRule;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.bean.rebuild.FriendListResultBean;
import com.eqdd.yiqidian.bean.rebuild.TipBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.rxbus2.RxBus;
import com.eqdd.yiqidian.rxbus2.Subscribe;
import com.eqdd.yiqidian.rxbus2.ThreadMode;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.ui.tongxunlu.AddFriendTypeActivity;
import com.eqdd.yiqidian.ui.tongxunlu.StaffActivity;
import com.eqdd.yiqidian.ui.tongxunlu.tag.TagActivity;
import com.eqdd.yiqidian.ui.tongxunlu.FriendApplyActivity;
import com.eqdd.yiqidian.ui.tongxunlu.TeamCheatListActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.IMUtil;
import com.eqdd.yiqidian.utils.ItemDecorationUtil;
import com.eqdd.yiqidian.utils.RefreshUtil;
import com.eqdd.yiqidian.utils.SideBarUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.gamerole.itemdecoration.lib.PinHeadItemDecoration;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.shizhefei.view.coolrefreshview.header.MaterialHeader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by lvzhihao on 17-4-7.
 */

public class TongxunluFragment extends BaseFragment {

    private TongxunluFragmentCustom dataBinding;
    private Class[] classes = new Class[]{
            AddFriendTypeActivity.class,
            StaffActivity.class,
            FriendApplyActivity.class,
            TeamCheatListActivity.class,
            TagActivity.class,
    };

    private User user;
    private LinearLayoutManager mLinearLayoutManager;
    private int deletePosition;
    private ActionSheetDialog alertView;
    private AlertDialog alerTiptDialog;
    private SlimAdapterEx slimAdapterEx;
    private ArrayList<TipBean> tipBeen;
    private List<FriendListResultBean> items;
    private PinHeadItemDecoration floatDeco;
    private Object dealCodeInjector;

    @DealCodeClass(classes = {FriendApplyActivity.class})
    public void updateFriendApply(int num) {
        TipBean dataItem = (TipBean) slimAdapterEx.getDataItem(2);
        dataItem.setNum(num);
        slimAdapterEx.notifyItemChanged(2);
    }

    @Subscribe(code = CodeRule.USER_INFO, threadMode = ThreadMode.MAIN)
    public void updateUser() {
        user = GreenDaoUtil.getUser();
    }

    @Subscribe(code = CodeRule.FRIEND_APPLY_AGREE, threadMode = ThreadMode.MAIN)
    public void updateFriend() {
        dataBinding.coolRefreshView.setRefreshing(true);
    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_tongxunlu, null, false);

    }

    @Override
    protected void initData() {
        dealCodeInjector = DealCodeInjector.register(this, RxBus.class);
        RxBus.getDefault().register(this);
        user = GreenDaoUtil.getUser();
        initHead();
    }

    @Override
    protected void setView() {
        initDialog();
        if (slimAdapterEx == null) {
            mLinearLayoutManager = new LinearLayoutManager(getActivity());
            dataBinding.recyclerView.setLayoutManager(mLinearLayoutManager);
            dataBinding.recyclerView.setItemAnimator(new DefaultItemAnimator());
            dataBinding.recyclerView.addItemDecoration(new SectionDividerItemDecoration(getActivity(), 5).setLeftPadding(180).setLastBootomHeght(0));
            floatDeco = ItemDecorationUtil.openPinDeco(getActivity(), dataBinding.recyclerView).textColor(getResources().getColor(R.color.colorPrimary));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_tongxunlu, new SlimInjector<FriendListResultBean>() {
                @Override
                public void onInject(FriendListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_content, data.getUpname())
                            .imageCircle(R.id.iv_head, data.getIphoto())
                            .clicked(R.id.iv_head, v -> {
                                Bundle bundle = new Bundle();
                                bundle.putString(Config.GUID, data.getGuid());
                                startActivity(UserCardActivity.class, bundle);
                            });
                }
            }).register(R.layout.list_item_15, new SlimInjector<TipBean>() {
                @Override
                public void onInject(TipBean data, IViewInjector injector) {
                    injector.text(R.id.tv_title, data.getTitle())
                            .image(R.id.iv_head, data.getResId());
                    if (data.getNum() > 0) {
                        injector.gone(R.id.drag_point_view);
                        injector.visible(R.id.red_dot);
                        injector.text(R.id.drag_point_view, data.getNum() + "");
                    } else {
                        injector.gone(R.id.drag_point_view);
                        injector.gone(R.id.red_dot);

                    }

                }
            }).attachTo(dataBinding.recyclerView).updateData(tipBeen);
            ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener(
                    (rv, position, v) -> {
                        if (slimAdapterEx.getDataItem(position) instanceof TipBean) {
                            TipBean dataItem = (TipBean) slimAdapterEx.getDataItem(position);
                            if (classes[position] != null) {
//                                if (dataItem.getNum() > 0) {
//                                    GreenDaoUtil.setNum(dataItem.getCode(), 0);
//                                }
                                startActivity(classes[position]);
                            }
                        } else {
                            IMUtil.startPrivate(getActivity(), ((FriendListResultBean) slimAdapterEx.getDataItem(position)).getGuid() + "",
                                    ((FriendListResultBean) slimAdapterEx.getDataItem(position)).getUpname() + "", ((FriendListResultBean) slimAdapterEx.getDataItem(position)).getIphoto());
                        }
                    }
            )
                    .setOnItemLongClickListener(
                            (rv, position, v) -> {
                                if (slimAdapterEx.getDataItem(position) instanceof FriendListResultBean) {
                                    deletePosition = position;
                                    alertView.show();
                                }
                                return true;

                            }
                    );
            RefreshUtil.openRefresh(dataBinding.coolRefreshView, coolRefreshView -> refresh());
            dataBinding.coolRefreshView.setPullHeader(new MaterialHeader(getActivity()));
            dataBinding.waveSideBar.setRecyclerView(dataBinding.recyclerView);
        }
        dataBinding.coolRefreshView.setRefreshing(true);
    }

    private void refresh() {
        OkGo.<HttpResult<List<FriendListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.FRIEND_LIST_INFO)
                .params("userGuid", user.getGuid())
                .execute(new JsonCallBack<HttpResult<List<FriendListResultBean>>>() {
                    @Override
                    public void onSuccess(Response<HttpResult<List<FriendListResultBean>>> response) {
                        HttpResult<List<FriendListResultBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            Collections.sort(httpResult.getItems());
                            items = httpResult.getItems();
                            ArrayList temp = new ArrayList();
                            temp.addAll(tipBeen);
                            temp.addAll(items);
                            slimAdapterEx.updateData(temp);
                            SideBarUtil.updateData(dataBinding.waveSideBar, slimAdapterEx.getData(), "upname");
                            ItemDecorationUtil.updateData(floatDeco, slimAdapterEx.getData(), "upname");
                            dataBinding.coolRefreshView.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Response<HttpResult<List<FriendListResultBean>>> response) {
                        super.onError(response);
                        dataBinding.coolRefreshView.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onClick(View view) {

    }

    private void initDialog() {
        if (alertView == null) {
            alertView = ChooseAlertView.getBottomChoose(getActivity(), "", new String[]{"删除好友", "拨打电话"}, (o, position) -> {
                switch (position) {
                    case 1:
                        if (alerTiptDialog == null) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setMessage("确认删除该好友吗?");
                            builder.setTitle("提示");
                            builder.setPositiveButton("确认", (dialog, which) -> {
                                dialog.dismiss();
                                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.FRIEND_DELETE)
                                        .params("userGuid", AppConstent.user.getGuid())
                                        .params("friendGuid", ((FriendListResultBean) slimAdapterEx.getDataItem(deletePosition)).getGuid())
                                        .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                                            @Override
                                            public void onSuccess(Response<HttpResult> response) {
                                                HttpResult httpResult = response.body();
                                                ToastUtil.showShort(httpResult.getMsg());
                                                if (httpResult.getStatus() == 200) {
                                                    refresh();
                                                }
                                            }
                                        });
                            });
                            builder.setNegativeButton("取消", (DialogInterface dialog, int which) -> {
                                        dialog.dismiss();
                                    }
                            );
                            alerTiptDialog = builder.create();
                        }
                        alerTiptDialog.show();

                        break;
                    case 2:
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + ((FriendListResultBean) slimAdapterEx.getDataItem(deletePosition)).getUname());
                        intent.setData(data);
                        startActivity(intent);
                        break;

                }
            });

        }
    }

    private void initHead() {
        tipBeen = new ArrayList<>();
        tipBeen.add(new TipBean(R.mipmap.ease_new_friends_icon, "添加好友", CodeRule.CODE_NULL));
        tipBeen.add(new TipBean(R.mipmap.mytask, "同事", CodeRule.CODE_NULL));
        tipBeen.add(new TipBean(R.mipmap.yanzheng, "好友申请", CodeRule.FRIEND_APPLY));
        tipBeen.add(new TipBean(R.mipmap.qun, "群聊", CodeRule.CODE_NULL));
        tipBeen.add(new TipBean(R.mipmap.biaoqian, "标签", CodeRule.CODE_NULL));
    }

    @Override
    public void onDestroy() {
        RxBus.getDefault().unregister(this);

        DealCodeInjector.unregister(this, RxBus.class, dealCodeInjector);
        super.onDestroy();
    }
}
